import { isStarted } from '../start'
import { getAppChanges } from '../applications/app.js'
import { toLoadPromise } from '../lifecycles/load.js'
import { toUnmountPromise } from '../lifecycles/unmount.js'
import { toBootstrapPromise } from '../lifecycles/bootstrap'
import {
  callCapturedEventListeners,
  navigateToUrl,
} from './navigation-events'
import { isInBrowser } from '../utils/runtime-environment'

let appChangeUnderway = false,
  peopleWaitingOnAppChange = [],
  currentUrl = isInBrowser && window.location.href

export function triggerAppChange () {
  return reroute()
}

export function reroute(pendingPromises = [], eventArguments) {
  // 需要获取 要加载的应用
  // 需要获取 要被挂载的应用
  //  哪些应用需要被挂载
  const { appsToUnmount, appsToLoad, appsToMount } = getAppChanges()

  if (isStarted()) {
    appChangeUnderway = true
    // app 装载
    return performanceAppChanges() // 根据路径来装载应用
  } else {
    // 注册应用，需要预先加载
    return loadApps() // 预加载应用
  }

  function loadApps() { // 预加载应用
    return Promise.resolve().then(() => {
      const loadPromises = appsToLoad.map(toLoadPromise)
      Promise.all(loadPromises)
    })
  }
  async function performanceAppChanges() { // 根据路径来装载应用
    // 先卸载不用的应用
    let unmountPromise = appsToUnmount.map(toUnmountPromise)
    // 去加载需要的应用
    appsToLoad.map(async (app) => { // 将需要加载的应用拿到 =》 启动 =》 挂载
      app = await toLoadPromise(app)
      app = await toBootstrapPromise(app)
      return await toMountPromise(app)
    })
    // 去挂载应用
    appsToMount.map(async (app) => {
      app = await toLoadPromise(app)
      return await toMountPromise(app)
    })
  }
}